package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.FarmerCustomOrder;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OrderView;
import com.hemaapp.yjnh.present.OrderPresent;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.DeliveryDialog;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomToastUtil;

/**
 * 买家和田家定制订单的详情
 * @author GuiyouZhang
 */
public class FarmerCustomOrderDetailActivity extends BaseActivity implements OrderView {

    private final static int REQUEST_PAY = 0x01;//去自己支付
    private final static int REQUEST_FRIEND = 0x02;//朋友代付
    private final static int REQUEST_ORDER_COMMIT = 0x03;//评价订单
    private final static int REQUEST_ORDER_AFTERSALE = 0x04;//申请售后

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_contact_name)
    TextView tvContactName;
    @Bind(R.id.tv_tel)
    TextView tvTel;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.layout_goods)
    LinearLayout layoutGoods;
    @Bind(R.id.tv_addition)
    TextView tvAddition;
    @Bind(R.id.tv_cash_stamp)
    TextView tvCashStamp;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_order_sn)
    TextView tvOrderSn;
    @Bind(R.id.tv_order_time)
    TextView tvOrderTime;
    @Bind(R.id.tv_express_name)
    TextView tvExpressName;
    @Bind(R.id.tv_express_num)
    TextView tvExpressNum;
    @Bind(R.id.tv_order_status)
    TextView tvOrderStatus;
    @Bind(R.id.layout_bottom)
    LinearLayout layoutBottom;
    @Bind(R.id.tv_send)
    TextView tvSend;
    @Bind(R.id.iv_edit_express)
    ImageView ivEditExpress;

    private OrderPresent present;
    private FarmerCustomOrder mOrder;//定制订单信息
    private User user;
    private ClientDetails details;//田主的详细信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_custom_order_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        present = new OrderPresent(mContext, this, getApplicationContext().getUser());
        mOrder = (FarmerCustomOrder) mIntent.getSerializableExtra("order");
        if (mOrder == null) {
            showTextDialog("参数错误!");
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1000);
        }else {
            setDatas(null);
        }
    }

    @Override
    protected void setListener() {
        titleText.setText("定制详情");
        titleRightBtn.setVisibility(View.GONE);
    }

    @OnClick({R.id.title_left_btn, R.id.tv_send, R.id.iv_edit_express})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.iv_edit_express:
            case R.id.tv_send:
                final DeliveryDialog deliveryDialog = new DeliveryDialog(mContext).builder();
                deliveryDialog.setClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String expressName = deliveryDialog.getExpressName();
                        String expressNum = deliveryDialog.getExpressNum();
                        if (isNull(expressName)) {
                            XtomToastUtil.showShortToast(mContext, "快递公司名称不能为空!");
                            return;
                        }
                        if (expressNum.isEmpty()) {
                            XtomToastUtil.showShortToast(mContext, "快递单号不能为空!");
                            return;
                        }
                        present.operateOrder(mOrder.getId(), "4", "无", "无", expressName, expressNum);
                        deliveryDialog.dismiss();
                    }
                });
                deliveryDialog.show();
                break;
        }
    }

    public void showConfirmDialog(String content, HemaButtonDialog.OnButtonListener listener) {
        HemaButtonDialog dialog = new HemaButtonDialog(mContext);
        dialog.setText(content);
        dialog.setLeftButtonText("取消");
        dialog.setRightButtonText("确定");
        dialog.setButtonListener(listener);
        dialog.show();
    }

    @Override
    public void beforeLoading() {
        showProgressDialog("请稍候");
    }

    @Override
    public void loadingFinish() {
        cancelProgressDialog();
    }

    @Override
    public void showAlertDialog(String title, String ok, BaseButtonDialog.OnButtonListener listener) {

    }

    @Override
    public void setDatas(Order order1) {
        tvContactName.setText("联系人：" + mOrder.getConsignee());
        tvTel.setText("电话：" + mOrder.getPhone());
        tvDate.setText("该定制商品发货时间：" + mOrder.getExpect_senddate());
        tvAddition.setText("¥" + uuUtils.formatAfterDot2(mOrder.getAddition_fee()));
        tvFreight.setText("¥" + uuUtils.formatAfterDot2(mOrder.getShipping_fee()));
        tvTotalFee.setText("¥" + uuUtils.formatAfterDot2(mOrder.getTotal_fee()));
        double goodsFee = 0.0;
        double stampFee = 0.0;
        try {
            goodsFee = Double.parseDouble(mOrder.getGoods_fee());
            stampFee = Double.parseDouble(mOrder.getScore_fee());
        }catch (Exception e) {
            e.printStackTrace();
        }
        tvCashStamp.setText("¥"+ uuUtils.formatAfterDot2(goodsFee-stampFee+"")+" + ");
        BaseUtil.addStampSign(mContext, tvCashStamp, R.drawable.food_stamp_grey);
        tvCashStamp.append(mOrder.getScore_fee()+"粮票");
        tvOrderSn.setText(mOrder.getBill_sn());
        tvOrderTime.setText(mOrder.getRegdate());
        tvExpressName.setText(mOrder.getShipping_name());
        tvExpressNum.setText(mOrder.getShipping_num());
        present.setStatusAndBottom(mOrder);
        if (!isNull(mOrder.getShipping_name()) && mOrder.getTradetype().equals("2"))//只有待收货的时候才能显示
            ivEditExpress.setVisibility(View.VISIBLE);
        else
            ivEditExpress.setVisibility(View.GONE);
        //动态添加多个商品
        if (layoutGoods.getChildCount() != 0) {
            layoutGoods.removeAllViews();
        }
        for (int i = 0; i < mOrder.getChildItems().size(); i++) {
            FarmerCustomOrder.ChildItemsBean child = mOrder.getChildItems().get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_goods, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            setItem(i, child, view, ivHolder);
            view.setTag(mOrder.getChildItems().get(i).getBlog_id());
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String blogId = (String) v.getTag();
                    // 先根据商品属性自己判断
//                    Intent intent = BaseUtil.createBlogIntent(mContext, child.getType());
                    Intent intent = new Intent(mContext, CustomizeProductionDetailActivity.class);
                    intent.putExtra("blog_id", blogId);
                    mContext.startActivity(intent);
                }
            });
        }
    }

    @Override
    public void onOrderOperateSuccess(String keytype) {
        if ("1".equals(keytype)) {
            showTextDialog("删除成功！");
        } else if ("2".equals(keytype)) {
            showTextDialog("确定收货成功！");
        } else if ("4".equals(keytype)) {
            showTextDialog("发货成功！");
        } else if ("3".equals(keytype) || "6".equals(keytype)) {
            showTextDialog("操作成功！");
        }
        EventBusMsg msg = new EventBusMsg();
        msg.setType(EventBusConfig.UPDATE_ORDER);
        EventBus.getDefault().post(msg);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                finish();
            }
        }, 500);
    }

    @Override
    public void setStatus(String status) {
        tvOrderStatus.setText(status);
    }

    /**
     * @param visibility 底部按钮的顺序依次为：
     *                   layoutBottom、确认收货、取消订单、代付、支付
     */
    @Override
    public void setBottomButton(int[] visibility) {
        layoutBottom.setVisibility(visibility[0]);
        if (visibility[0] == View.VISIBLE) {
            tvSend.setVisibility(visibility[1]);
        }
    }

    private class ItemViewHolder {
        private ImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        TextView tvCommit;
        TextView tvAfterSale;
        TextView tvHint;
        View div;
    }

    /**
     * 一个订单中的多个商品
     *
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.img = (ImageView) view.findViewById(R.id.img);
        ivHolder.name = (TextView) view.findViewById(R.id.good_name);
        ivHolder.price = (TextView) view.findViewById(R.id.price);
        ivHolder.amount = (TextView) view.findViewById(R.id.count);
        ivHolder.tvCommit = (TextView) view.findViewById(R.id.tv_commit);
        ivHolder.tvAfterSale = (TextView) view.findViewById(R.id.tv_aftersale);
        ivHolder.tvHint = (TextView) view.findViewById(R.id.tv_hint);
        ivHolder.div = view.findViewById(R.id.divider);
    }

    private void setItem(int i, final  FarmerCustomOrder.ChildItemsBean child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText("¥" + uuUtils.formatAfterDot2(child.getPrice()));
        ivHolder.amount.setText("x" + child.getBuycount());

        if (i == mOrder.getChildItems().size() - 1) {
            ivHolder.div.setVisibility(View.GONE);
        } else {
            ivHolder.div.setVisibility(View.VISIBLE);
        }
        ivHolder.tvCommit.setVisibility(View.GONE);
        ivHolder.tvAfterSale.setVisibility(View.GONE);
        layoutGoods.addView(view);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PAY:
            case REQUEST_FRIEND:
            case REQUEST_ORDER_COMMIT:
            case REQUEST_ORDER_AFTERSALE:
                present.getOrderDetail(mOrder.getId());
                break;
            default:
                break;
        }
    }
}
